<template>
	<div
		class="table-wrap relative w-full transition-all duration-500 overflow-auto"
		:style="['height:' + c_height + 'px']"
	>
		<div class="table-head-wrap" ref="tableHeadRef" style="height: 50px">
			<table class="table-head">
				<colgroup>
					<col
						v-for="col in columns"
						:key="col.key"
						:style="{ width: col.width + 'px' }"
					/>
				</colgroup>
				<thead>
					<tr>
						<th v-for="col in columns" :key="col.key">{{ col.title }}</th>
					</tr>
				</thead>
			</table>
		</div>

		<div class="table-body-wrap" ref="tableBodyRef" style="max-height: 250px">
			<table class="table-body">
				<colgroup>
					<col
						v-for="col in columns"
						:key="col.key"
						:style="{ width: col.width + 'px' }"
					/>
				</colgroup>
				<tbody>
					<tr v-for="d in data" :key="d.id">
						<td v-for="col in columns" :key="col.key">
							{{ col.render ? col.render(d[col.dataKey]) : d[col.dataKey] }}
						</td>
					</tr>
				</tbody>
			</table>
		</div>
	</div>
</template>
<script setup>
import { onMounted, onUnmounted, ref } from 'vue';

const { columns, data } = defineProps(['columns', 'data']);
const c_height = Math.min((data.length + 1) * 50, 300);

const tableBodyRef = ref(),
	tableHeadRef = ref();
let lastLeft = 0;
const handleScroll = () => {
	if (tableBodyRef.value.scrollLeft !== lastLeft) {
		lastLeft = tableBodyRef.value.scrollLeft;
		tableHeadRef.value.scrollTo(lastLeft, 0);
	}
};
onMounted(() => {
	tableBodyRef.value.addEventListener('scroll', handleScroll);
});

onUnmounted(() => {
	tableBodyRef.value.removeEventListener('scroll', handleScroll);
});
</script>
<style>
.table-wrap {
	overflow: hidden;
}
.table-head,
.table-body {
	width: 950px;
	min-width: 100%;
}
.table-head th,
.table-body td {
	font-size: 14px;
}
.table-head th,
.table-body td {
	border-bottom-width: 1px;
	border-color: #ebeef5;
	border-style: solid;
	text-align: left;
	padding: 0 12px;
	height: 50px;
}

.table-head-wrap {
	width: 100%;
	overflow: hidden;
	color: #909399;
}

.table-body-wrap {
	overflow: auto;
	width: 100%;
}

.table-head-wrap::-webkit-scrollbar,
.table-body-wrap::-webkit-scrollbar {
	width: 6px;
	height: 6px;
}

.table-head-wrap::-webkit-scrollbar-thumb,
.table-body-wrap::-webkit-scrollbar-thumb {
	background: #dddee0;
	border-radius: 10px;
	opacity: 0.5;
}

.table-head,
.table-body {
	width: 950px;
}
</style>
